<?php

namespace App\Http\Controllers\Admin;

use App\Http\Response;
use App\Merchant;
use App\News;
use App\Order;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class MerchantController extends Controller
{
    use Response;
    public function index(Request $request)
    {

        $result=Merchant::with('user')->paginate($request->get('pageSize'),'*','pageNo');
        return $this->success(200,$result);

    }
    public function store(Request $request)
    {
        $data=$request->except("goods");
        $find=Merchant::where('uid',$data['uid'])->first();
        if ($find){
            return $this->error(505,'用户已绑定经销商,创建失败');
        }
        $created=Merchant::create($data);
        if ($created){
            User::where('id',$data['uid'])->update(['is_merchant'=>1]);
            return $this->message(200,'创建成功');
        }else{
            return $this->error(505,'创建失败');
        }
    }
    public function show($id)
    {
        $result=Merchant::find($id);
        return $this->success(200,$result);
    }
    public function update($id,Request $request)
    {
        $update=Merchant::where('id',$id)->update($request->all());
        if ($update){
            if ($request->get('uid')){
                User::where('id',$request->get('uid'))->update(['is_merchant'=>1]);
            }
            return $this->message(200,'更新成功');
        }else{
            return $this->error(505,'更新失败');
        }
    }
    public function destroy($id)
    {
        $find=Merchant::find($id);
        $delete=Merchant::destroy($id);
        User::where('id',$find['uid'])->update(['is_merchant'=>0]);
        if ($delete){
            return $this->message(200,'删除成功');
        }else{
            return $this->error(505,'删除失败');
        }
    }
}
